package org.game.module.fight.handler;

import java.util.List;

import org.cfg.DungeonLevelCfg;
import org.cfg.DungeonLevelGroupCfg;
import org.cfg.cache.DiscreteDataCfgCache;
import org.constant.DiscreteDataID;
import org.constant.DiscreteDataKey;
import org.constant.FormationConstant;
import org.game.db.bean.DungeonLevel;
import org.game.db.bean.Formation;
import org.game.db.bean.Player;
import org.game.db.bean.PlayerData;
import org.game.db.cache.FormationCache;
import org.game.db.cache.PlayerDataCache;
import org.game.log.LogDungeon;
import org.game.log.builder.LogDsp;
import org.game.log.dsp.DungeonDsp;
import org.game.log.dsp.GoodsDsp;
import org.game.manager.ItemManager;
import org.game.module.dungeonbo.DungeonBO;
import org.game.module.fight.AbstractFight;
import org.game.module.fight.dungeom.DungeonCheck;
import org.game.msgBuilder.DungeonMsgBuilder;
import org.game.protobuf.c2s.C2SDungeonMsg;
import org.game.protobuf.s2c.S2CDungeonMsg.FightOverMsg;
import org.game.protobuf.s2c.S2CDungeonMsg.FightStartMsg;
import org.game.protobuf.s2c.S2CItemMsg;
import org.game.protobuf.s2c.S2CShareMsg.RewardsMsg;
import org.utils.RemoteUtil;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.manager.MessageManager;
import com.xiaoleilu.hutool.date.DateUnit;

/**
 * @author : DengYing
 * @CreateDate : 2018年8月15日 下午3:54:25
 * @Description ：Please describe this document
 */
public abstract class DungeonFightHandler implements FightHandler{
	protected Player player;
	protected DungeonLevelCfg cfg;
	protected DungeonLevel dungeonLevel;
	protected DungeonLevelGroupCfg dungeonLevelGroupCfg;
	
	public DungeonFightHandler(Player player, DungeonLevelCfg cfg, DungeonLevel dungeonLevel,DungeonLevelGroupCfg dungeonLevelGroupCfg) {
		super();
		this.player = player;
		this.cfg = cfg;
		this.dungeonLevel = dungeonLevel;
		this.dungeonLevelGroupCfg = dungeonLevelGroupCfg;
	}

	
	@Override
	public void fightStart(AbstractFight fight) {
		FightStartMsg fightStartMsg = DungeonMsgBuilder.getFightStartMsg(cfg.getId(),fight);
		IMessage msg = MessageManager.me().create(DungeonBO.fightStart, fightStartMsg.toByteArray());
		player.getPlayerProxy().sendMsg(msg);
		
//		Formation formation = FormationCache.me().getByPlayerIdType(player.getId(), FormationConstant.TYPE_MAIN);
//		LogDungeon.me().log(player.getId(), cfg.getId(), cfg.getDungeonType(), fight.isWin(), LogDsp.newBuilder(DungeonDsp.FIGHT_START).addAttr("heroCount", formation.getStance().size()));
	}


	@Override
	public boolean overCheck(AbstractFight fight) {
		return true;
	}


	@Override
	public boolean startCheck(AbstractFight fight) {
		return true;
	}


	@Override
	public void fightOver(AbstractFight fight) {
		// 触发战斗事件
		int oldStar = fight.getAttr("oldStar",dungeonLevel.getStar());
		int nowStar = fight.getAttr("nowStar",dungeonLevel.getStar());
		if (fight.isWin()) {
			C2SDungeonMsg.FightOverMsg submitMsg = fight.getAttr("submit");
			DungeonCheck.fightEvent(player, dungeonLevel, oldStar, nowStar, cfg, submitMsg);
		}
		
		Formation formation = FormationCache.me().getByPlayerIdType(player.getId(), FormationConstant.TYPE_MAIN);
		LogDungeon.me().log(player.getId(), cfg.getId(), cfg.getDungeonType(), fight.isWin(), LogDsp.newBuilder(DungeonDsp.FIGHT_OVER).addAttr("oldStar", oldStar).addAttr("nowStar", nowStar).addAttr("heroCount", formation.getStance().size()));
	}

	@Override
	public void fightWin(AbstractFight fight) {
		C2SDungeonMsg.FightOverMsg submitMsg = fight.getAttr("submit");
		
		List<Integer> goals = submitMsg.getGoalsList();
//		DungeonLevel dungeonLevel = initOrGetDungeonLevel(player, cfg.getId());
		dungeonLevel.setWin(fight.isWin());
	    dungeonLevel.setFightCount(dungeonLevel.getFightCount() + 1);
	    if(goals != null && goals.size() > 0){
            goals.forEach(g->{
                if(!dungeonLevel.getAchieveGoals().contains(g)){
                    dungeonLevel.getAchieveGoals().add(g);
                }
            });
        }
	    fight.setAttr("oldStar", dungeonLevel.getStar());
	    dungeonLevel.setStar(dungeonLevel.getAchieveGoals().size());
        dungeonLevel.setTotalFightCount(dungeonLevel.getTotalFightCount() +1);
        dungeonLevel.update();
        fight.setAttr("nowStar", dungeonLevel.getStar());

        pushRewards(fight);
		dealHelpFighter(fight,player);
	}


	protected void pushRewards(AbstractFight fight) {
		// 扣除消耗
	    LogDsp log = LogDsp.newBuilder(GoodsDsp.DUP_FIGHT).targetTag(dungeonLevel.getCid());
	    LogDsp cloneLog = log.clone();
        ItemManager.costGoodsByCid(player, dungeonLevel.getDungeonLevelProxy().getCfg().getCost(), log, S2CItemMsg.ItemList.newBuilder());
	   
        // 发放奖励
	    List<RewardsMsg> rewardsMsgs = ItemManager.unpackNotify(player, fight.getRewards(), cloneLog);
	    
	    // 下发成功消息
	    FightOverMsg fightOverMsg = DungeonMsgBuilder.getFightWinMsg(dungeonLevel, rewardsMsgs);
	    IMessage msg = MessageManager.me().create(DungeonBO.fightOver, fightOverMsg.toByteArray());
		player.getPlayerProxy().sendMsg(msg);
	}

	@Override
	public void fightFail(AbstractFight fight) {
		// 下发失败消息
		FightOverMsg fightOverMsg = DungeonMsgBuilder.getFightFailMsg(dungeonLevel);	
		IMessage msg = MessageManager.me().create(DungeonBO.fightOver, fightOverMsg.toByteArray());
		player.getPlayerProxy().sendMsg(msg);
	}

	/**
	 * 处理助战玩家
	 * */
	void dealHelpFighter(AbstractFight fight, Player player){
		if (fight.getHelpPid() != 0){
			RemoteUtil.socialAsyn().rewardFriendPoint(player.getId(),fight.getHelpPid());
			PlayerData pd = PlayerDataCache.me().getByPlayerId(player.getId());
			int cd = DiscreteDataCfgCache.me().getIntData(DiscreteDataID.HELP_FIGHTER, DiscreteDataKey.HELP_CD);
			pd.getPlayerDataProxy().getDiscreteVO().getHelpFighterColdTimeMap().put(fight.getHelpPid(), System.currentTimeMillis()+cd* DateUnit.MINUTE.getMillis());
			pd.update();
		}
	}
	
	
	
	
//	/** 获取关卡记录 */
//	protected DungeonLevel initOrGetDungeonLevel(Player player, int cid) {
//        DungeonLevel dungeonLevel = DungeonLevelCache.me().getDungeonLevelCacheProxy().getByPlayerIdCid(player.getId(), cid);
//        if (dungeonLevel == null) {
//            dungeonLevel = new DungeonLevel(0L, player.getId(), cid, 0, 0, false,Lists.newArrayList(),new Date(),0);
//            dungeonLevel.insert();
//        }
//        return dungeonLevel;
//    }
}
